import React, { useState, useEffect } from 'react';
import { Drawer, Form, Input, InputNumber, Select, Switch, Button, Space, Divider, Typography, Tag, Alert, Tabs, Collapse, Slider } from 'antd';
import { Model, useModelsStore } from '../../stores/modelsStore';
import { ApiOutlined, SettingOutlined, LaptopOutlined, CloudOutlined, QuestionCircleOutlined, InfoCircleOutlined, SaveOutlined } from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;

interface ModelConfigDrawerProps {
  model: Model | null;
  visible: boolean;
  onClose: () => void;
}

const ModelConfigDrawer: React.FC<ModelConfigDrawerProps> = ({ model, visible, onClose }) => {
  const [form] = Form.useForm();
  const { updateModelConfig } = useModelsStore();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');
  
  useEffect(() => {
    if (model && visible) {
      const initialValues = {
        apiKey: model.apiKey || '',
        temperature: model.parameters?.temperature || 0.7,
        topP: model.parameters?.topP || 0.9,
        maxTokens: model.maxTokens || 4096,
      };
      form.setFieldsValue(initialValues);
    }
  }, [model, form, visible]);
  
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 更新模型配置
      await updateModelConfig(model?.id || '', {
        apiKey: values.apiKey,
        parameters: {
          ...model?.parameters,
          temperature: values.temperature,
          topP: values.topP,
        },
        maxTokens: values.maxTokens
      });
      
      setLoading(false);
      onClose();
    } catch (error) {
      console.error('保存模型配置失败:', error);
      setLoading(false);
    }
  };
  
  // 渲染Ollama特定配置
  const renderOllamaConfig = () => {
    if (!model || model.provider !== 'Ollama') return null;
    
    return (
      <>
        <Form.Item name="ollamaServerUrl" label="Ollama服务器地址" 
          help="本地Ollama服务器的地址，默认为 http://localhost:11434"
        >
          <Input placeholder="http://localhost:11434" />
        </Form.Item>
        
        <Form.Item name="ollamaModelFile" label="模型文件路径" 
          help="Modelfile的路径，用于自定义模型配置（可选）"
        >
          <Input placeholder="/path/to/Modelfile" />
        </Form.Item>
        
        <Form.Item name="gpuLayers" label="GPU层数" 
          help="使用GPU加速的层数（0表示完全使用CPU）"
        >
          <InputNumber min={0} max={100} style={{ width: '100%' }} />
        </Form.Item>
        
        <Form.Item name="contextSize" label="上下文大小" 
          help="模型的上下文大小，影响内存使用量和性能"
        >
          <InputNumber min={512} max={16384} step={512} style={{ width: '100%' }} />
        </Form.Item>
      </>
    );
  };
  
  // 渲染OpenAI特定配置
  const renderOpenAIConfig = () => {
    if (!model || model.provider !== 'OpenAI') return null;
    
    return (
      <>
        <Form.Item name="organization" label="组织ID" 
          help="OpenAI组织ID（如适用）"
        >
          <Input placeholder="org-..." />
        </Form.Item>
        
        <Form.Item name="deploymentName" label="部署名称" 
          help="Azure OpenAI部署名称（仅Azure OpenAI）"
        >
          <Input />
        </Form.Item>
        
        <Form.Item name="useAzure" label="使用Azure OpenAI" valuePropName="checked">
          <Switch />
        </Form.Item>
      </>
    );
  };
  
  // 渲染特定模型类型的配置表单
  const renderModelTypeConfig = () => {
    if (!model) return null;
    
    switch (model.type) {
      case 'llm':
        return (
          <>
            <Form.Item
              name="temperature"
              label={
                <Space>
                  <span>温度 (Temperature)</span>
                  <Text type="secondary">更高的值会使输出更随机</Text>
                </Space>
              }
            >
              <Slider
                min={0}
                max={2}
                step={0.1}
                marks={{
                  0: '精确',
                  1: '平衡',
                  2: '创造性'
                }}
              />
            </Form.Item>
            
            <Form.Item
              name="topP"
              label={
                <Space>
                  <span>Top P</span>
                  <Text type="secondary">控制输出的多样性</Text>
                </Space>
              }
            >
              <Slider
                min={0}
                max={1}
                step={0.05}
                marks={{
                  0: '确定性',
                  0.5: '平衡',
                  1: '多样性'
                }}
              />
            </Form.Item>
            
            <Form.Item
              name="maxTokens"
              label="最大Token数"
              extra="限制模型生成的最大Token数量"
            >
              <InputNumber
                min={1}
                max={100000}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </>
        );
        
      case 'embedding':
        return (
          <>
            <Form.Item name="dimensions" label="向量维度">
              <InputNumber min={1} max={4096} disabled={model.provider !== 'custom'} style={{ width: '100%' }} />
            </Form.Item>
            
            <Form.Item name="similarityMetric" label="相似度度量">
              <Select>
                <Option value="cosine">余弦相似度</Option>
                <Option value="euclidean">欧几里得距离</Option>
                <Option value="dot">点积</Option>
              </Select>
            </Form.Item>
            
            <Form.Item name="normalize" label="向量归一化" valuePropName="checked"
              help="是否对生成的嵌入向量进行归一化处理"
            >
              <Switch />
            </Form.Item>
          </>
        );
        
      case 'search':
        return (
          <>
            <Form.Item name="indexName" label="索引名称">
              <Input />
            </Form.Item>
            
            <Form.Item name="topK" label="返回结果数">
              <InputNumber min={1} max={100} style={{ width: '100%' }} />
            </Form.Item>
            
            <Form.Item name="scoreThreshold" label="相似度阈值">
              <InputNumber min={0} max={1} step={0.01} style={{ width: '100%' }} />
            </Form.Item>
          </>
        );
        
      default:
        return (
          <Alert message="未知模型类型" type="warning" />
        );
    }
  };
  
  if (!model) return null;
  
  return (
    <Drawer
      title={
        <Space>
          {model.provider === 'OpenAI' ? <CloudOutlined /> : 
           model.provider === 'Ollama' ? <LaptopOutlined /> : 
           <ApiOutlined />}
          <span>{`模型配置 - ${model.name}`}</span>
        </Space>
      }
      width={600}
      open={visible}
      onClose={onClose}
      footer={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" icon={<SaveOutlined />} loading={loading} onClick={handleSave}>
            保存配置
          </Button>
        </Space>
      }
    >
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Tag color={model.type === 'llm' ? 'blue' : model.type === 'embedding' ? 'green' : 'purple'}>
            {model.type === 'llm' ? '语言模型' : model.type === 'embedding' ? '嵌入模型' : '搜索模型'}
          </Tag>
          <Tag color={
            model.provider === 'OpenAI' ? 'green' :
            model.provider === 'Ollama' ? 'red' :
            model.provider === 'Anthropic' ? 'purple' :
            model.provider === 'HuggingFace' ? 'orange' :
            'default'
          }>{model.provider}</Tag>
          {model.costPerRequest === 0 && <Tag color="success">免费</Tag>}
          {model.provider === 'Ollama' && (
            <Tag color="volcano" icon={<LaptopOutlined />}>本地</Tag>
          )}
        </Space>
      </div>
      
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="基本信息" key="basic">
          <Form
            form={form}
            layout="vertical"
            initialValues={model}
          >
            <Form.Item name="description" label="描述">
              <TextArea rows={2} />
            </Form.Item>
            
            <Divider orientation="left">状态</Divider>
            
            <Form.Item name="isActive" label="设为活跃模型" valuePropName="checked">
              <Switch />
            </Form.Item>
            
            <Form.Item name="isFavorite" label="收藏" valuePropName="checked">
              <Switch />
            </Form.Item>
            
            {model.provider === 'Ollama' && (
              <Alert
                message="本地部署模型"
                description="该模型通过Ollama在本地运行，无需API密钥，但需要先下载模型。"
                type="info"
                showIcon
                icon={<LaptopOutlined />}
                style={{ marginTop: 16 }}
              />
            )}
          </Form>
        </TabPane>
        
        <TabPane tab="API设置" key="api">
          <Form
            form={form}
            layout="vertical"
            initialValues={model}
          >
            {model.provider !== 'Ollama' && (
              <>
                <Form.Item
                  name="apiKey"
                  label="API密钥"
                  rules={[{ message: 'API密钥格式不正确' }]}
                  extra={`${model.provider} API密钥，用于访问${model.provider}的API服务`}
                >
                  <Input.Password placeholder={`请输入${model.provider} API密钥`} />
                </Form.Item>
                
                <Form.Item name="baseUrl" label="API基础URL">
                  <Input placeholder="输入API基础URL" />
                </Form.Item>
              </>
            )}
            
            {renderOllamaConfig()}
            {renderOpenAIConfig()}
          </Form>
        </TabPane>
        
        <TabPane tab="模型参数" key="params">
          <Form
            form={form}
            layout="vertical"
            initialValues={model}
          >
            {renderModelTypeConfig()}
          </Form>
        </TabPane>
        
        <TabPane tab="高级" key="advanced">
          <Form
            form={form}
            layout="vertical"
            initialValues={model}
          >
            <Form.Item name="timeout" label="请求超时（秒）">
              <InputNumber min={1} max={300} style={{ width: '100%' }} />
            </Form.Item>
            
            <Form.Item name="concurrencyLimit" label="并发请求数限制">
              <InputNumber min={1} max={50} style={{ width: '100%' }} />
            </Form.Item>
            
            <Form.Item name="retryAttempts" label="失败重试次数">
              <InputNumber min={0} max={5} style={{ width: '100%' }} />
            </Form.Item>
            
            {model.provider === 'Ollama' && (
              <Collapse ghost style={{ marginTop: 16 }}>
                <Panel header="高级Ollama设置" key="1">
                  <Form.Item name="mirostat" label="Mirostat算法" 
                    help="Mirostat采样算法版本（0禁用，1启用）"
                  >
                    <Select>
                      <Option value={0}>禁用</Option>
                      <Option value={1}>V1</Option>
                      <Option value={2}>V2</Option>
                    </Select>
                  </Form.Item>
                  
                  <Form.Item name="mirostatTau" label="Mirostat Tau">
                    <InputNumber min={0} max={10} step={0.1} style={{ width: '100%' }} />
                  </Form.Item>
                  
                  <Form.Item name="mirostatEta" label="Mirostat Eta">
                    <InputNumber min={0} max={1} step={0.01} style={{ width: '100%' }} />
                  </Form.Item>
                  
                  <Form.Item name="numCtx" label="上下文窗口大小">
                    <InputNumber min={512} max={32768} step={512} style={{ width: '100%' }} />
                  </Form.Item>
                </Panel>
              </Collapse>
            )}
          </Form>
        </TabPane>
      </Tabs>
    </Drawer>
  );
};

export default ModelConfigDrawer; 